/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.mochaccino.framework.util;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Purpose of the JNDI Binder is bind a Bean to a JNDI Name
 * for 3rd-party component that only support JNDI-Based Injection to work properly.
 * <p/>
 * For example, you may want to register the User Transaction to it's proper JNDI
 * name for Hibernate.
 */
public final class JndiBinder {

	private static final Logger  logger  = LoggerFactory.getLogger( JndiBinder.class );
	private              Context context = null;
	private              String  name    = null;
	private              Object  object  = null;

	/** Constructor */
	public JndiBinder( String name, Object object ) throws NamingException {
		this( new InitialContext(), name, object );
	}

	/** Constructor */
	public JndiBinder( Context context, String jndiName, Object jndiObject ) {
		this.context = context;
		this.name = jndiName;
		this.object = jndiObject;
	}

	/** Bind Object */
	public void bind() throws Exception {
		try {
			Object o = context.lookup( name );
			if ( o != null ) {
				throw new RuntimeException( "An object is already bound for name '" + name + "'" );
			}
		} catch ( NamingException e ) {
			logger.trace( e.getMessage(), e );
		}
		context.bind( name, object );
	}

	/** Unbind */
	public void unbind() throws Exception {
		try {
			Object o = context.lookup( name );
			if ( o != null && o == object ) {
				context.unbind( name );
			}
		} catch ( NamingException e ) {
			logger.error( e.getMessage(), e );
		}
	}
}
